
let myPdf=[],myPdfItem = {name: '', url: '', id: ''}
let myPdfs=[],myPdfItems = {name: '', url: '', id: ''}


let applyForms=$('#applyForms').val()
applyForms=null==applyForms?[]:applyForms.split(',')
for (let i = 0; i < applyForms.length; i++) {
    myPdfItem={
        name: applyForms[i].substr(applyForms[i].lastIndexOf('/')),
        id:i+'-0',
        url: applyForms[i]
    }
    myPdf.push(myPdfItem)
}

let ImageList=$('#ImageList').val()
ImageList=null==ImageList?[]:ImageList.split(',')
for (let i = 0; i < ImageList.length; i++) {
    myPdfItems={
        name: ImageList[i].substr(ImageList[i].lastIndexOf('/')),
        id:i+'-0',
        url: ImageList[i]
    }
    myPdfs.push(myPdfItems)
}


layui.use(['form', 'xmSelect', 'upload', 'laydate','table'], function () {
    var form = layui.form;
    var layer = layui.layer,myInviteeId='',myInviteeList=[],pages=0
    var xmSelect = layui.xmSelect,laydate = layui.laydate,upload = layui.upload;

    let div=$('.layui-input-block')
    for (let i = 0; i < div.length; i++) {
        if(''==$(div[i]).text()){
            $(div[i]).text('-')
        }
    }


    let myType1=[]
    const _setId=(myId)=>{
        let item=myType1.filter(item=>item.value==myId)
        if(item[0].text=="市州组"){
            $('#school').hide()
            $('#city').show()

        }else{
            $('#school').show()
            $('#city').hide()
        }
    }
    const _setType2=(value,myId)=>{
        //type2
        $('#type2').attr("disabled", true);
        AjaxGet(`/jzweb/jazSignupItem/list?groupId=${value}`).then( (response)=> {
            $('#type2').empty();
            $('#type2').append($('<option>', {
                value: '',
                text: '请选择参赛项目类型'
            }))
            response.data.forEach(item => {
                $('#type2').append($('<option>', {
                    value: item.id,
                    text: item.name,
                    selected: item.id== myId
                }))
            })

            $('#type2').attr("disabled", 'infor'==$('#myType').val());
            form.render('select');

        }).catch(function (error) {
            layer.msg(error.msg)
        })
    }

    const _setTeamName=(groupId,myId)=>{
        //type2
        $('#teamName1').attr("disabled", true);
        AjaxGet(`/jzweb/jazSignupTeam/selTeamList?groupId=${groupId}`).then( (response)=> {
            $('#teamName1').empty();
            $('#teamName1').append($('<option>', {
                value: '',
                text: '请选择队伍名称'
            }))
            response.data.forEach(item => {
                $('#teamName1').append($('<option>', {
                    value: item.id,
                    text: item.name,
                    selected: item.id== myId
                }))
            })

            $('#teamName1').attr("disabled", 'infor'==$('#myType').val());
            form.render('select');

        }).catch(function (error) {
            layer.msg(error.msg)
        })
    }

    $('#type1').attr("disabled", true);
    AjaxGet("/jzweb/jazSignupGroup/list").then(function (response) {
        //设置select
        $('#type1').empty();
        $('#type1').append($('<option>', {
            value: '',
            text: '请选择所属组别'
        }))
        myType1=[]
        response.data.forEach(item => {
            $('#type1').append($('<option>', {
                value: item.id,
                text: item.name,
                selected:item.id== $('#type1').attr("my-id")
            }))
            myType1.push({
                value: item.id,
                text: item.name,
            })
        })
        $('#type1').attr("disabled",true);
        form.render('select');
        _setId($('#type1').attr("my-id"))
    }).catch(function (error) {
        layer.msg(error.msg)
    })
    _setType2($('#type1').attr("my-id"),$('#type2').attr("my-id"))
    if($('#myType1').val()=='2'){
        _setTeamName($('#type1').attr("my-id"),$('#teamName1').attr("my-id"))
    }
    form.on('select(type1)', function(data){
        var elem = data.elem; // 获得 select 原始 DOM 对象
        var value = data.value; // 获得被选中的值
        $('#type2').attr("disabled", true);
        $('#type2').empty();
        if(value){
            _setType2(value,null)
            _setId(value)
            _setTeamName(value,null)
        }else{
            $('#type2').append($('<option>', {
                value: '',
                text: '请先选择所属组别'
            }))
        }
        $('#type2').attr("disabled", 'infor'==$('#myType').val());
        form.render('select');

    });
    form.on('select(city)', function(data){
        var value = data.value; // 获得被选中的值
        $('#teamName').val(value+'代表队')
    });
    $('#school').keyup(()=>{
        $('#teamName').val($('#school').val()+'代表队')
    })

    upload.render({
        elem: '#myUpdata'
        , url: '/common/sysFile/upload'
        , accept: 'file'
        // , exts: 'doc|docx'
        // , exts: 'pdf'
        // , multiple: true
        , acceptMime: 'application/msword'
        // , acceptMime: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document''application/pdf'
        , before: function (obj) {
            if(myPdf.length>=1000){
                layer.msg('上传已达上限，请删除在传')
                return false;
            }
            var files = this.files = obj.pushFile();  //将每次选择的文件追加到文件队列
            for (var key in files) {
                if (!myPdf.find(item => item.id == key)) {
                    myPdfItem = {name: '', url: '', id: ''}
                    // myPdfItem.name = files[key].name
                    myPdfItem.name ='文件'
                    myPdfItem.id = key
                }
            }
            //读取本地文件
            obj.preview(function (index, file, result) {
                console.log(file.Name);
            });
            loading = layer.load({
                type: 3,
                content: '加载中...',
            });//在post之前定义loading
        }
        , done: function (res, index) {
            layer.close(loading);
            if (res.code == 0) {
                if(myPdf.length<1000){
                    layer.msg('上传成功');
                    myPdfItem.url = res.data
                    myPdf.push(myPdfItem)
                    delete this.files[index]
                    $('#myUpdataList').prepend(`
				<div href="#"  style="margin:5px 10px;width: 100px;position: relative; display: flex;  flex-direction: column;  justify-content: center;  align-items: center;   
				height: 100px;border: 1px solid #000;" myid="${myPdfItem.id}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" style="    width: 50px;height: 50px" src="/img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide">
						<a style=" position: absolute; right: 0; top: 0;width: 20px; height: 20px;" href="#" onclick="removeImg(${myPdfItem.id});"> 
						<img style="    width: inherit;height: inherit"  class="closeUpload" src="/img/close.png" >	
						</a>
				</div>
				`)
                }else {
                    layer.msg('上传已达上限，请删除在传')
                }
            } else {
                layer.msg('上传失败,请检查');
            }

        }
    })
    upload.render({
        elem: '#myUpdataImage'
        , url: '/common/sysFile/upload'
        , accept: 'images'
        , exts: 'jpg|jpeg|png|gif'
        // , multiple: true
        // , acceptMime: 'application/img'
        // , acceptMime: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document''application/pdf'
        , before: function (obj) {
            if(myPdfs.length>=1){
                layer.msg('上传已达上限，请删除在传')
                return false;
            }
            var files = this.files = obj.pushFile();  //将每次选择的文件追加到文件队列
            for (var key in files) {
                if (!myPdfs.find(item => item.id == key)) {
                    myPdfItems = {name: '', url: '', id: ''}
                    // myPdfItem.name = files[key].name
                    myPdfItems.name ='文件'
                    myPdfItems.id = key
                }
            }
            //读取本地文件
            obj.preview(function (index, file, result) {
                console.log(file.Name);
            });
            loading = layer.load({
                type: 3,
                content: '加载中...',
            });//在post之前定义loading
        }
        , done: function (res, index) {
            layer.close(loading);
            if (res.code == 0) {
                if(myPdfs.length<1){
                    layer.msg('上传成功');
                    myPdfItems.url = res.data
                    myPdfs.push(myPdfItems)
                    delete this.files[index]
                    $('#myUpdataImageList').prepend(`
                    <div class="layui-inline mybutton" style="padding: 0" myid="${myPdfItems.id}" >
                            <img class="upImg" src="${myPdfItems.url}" style="height: 100%;width: 100%">
                            <input  value="${myPdfItems.id}" class="layui-hide">
                            <a style=" position: absolute; right: 0; top: 0;width: 20px; height: 20px;" href="#" 
                             onclick="removeImgs(${myPdfItems.id})">
                                <img style="    width: inherit;height: inherit"  class="closeUpload" src="/img/close.png" >
                            </a>
                        </div> `)
                }else {
                    layer.msg('上传已达上限，请删除在传')
                }
            } else {
                layer.msg('上传失败,请检查');
            }

        }
    })
    laydate.render({
        elem: '#birthday',
        rangeLinked: true,
        type: 'date',
        format: 'yyyy/MM/dd'
    });


    //提交事件
    form.on('submit(submit)', function (data) {
        let myParams={...data.field}
        myParams.id=$('#userId').val()
        console.log(myParams)
        if($('#myType').val()=='infor'){
            AjaxPost('/jzweb/jazSignupUser/update', {
                id:$('#userId').val(),
                status:2,
                result:1
            }).then(function (response) {
                parent.layer.msg("操作成功");
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                parent.load();
            }).catch(error => {
                layer.msg(error.msg)
            })
        }else{
            //
            let item=myType1.filter(item=>item.value==myParams.groupId)
            if(item[0].text=="市州组"){
                if(myParams.city==''){
                    layer.msg("请输入所属市州（院校名称）");
                    return false;
                }
            }else{
                if(myParams.school==''){
                    layer.msg("请输入所属市州（院校名称）");
                    return false;
                }
            }



            if(myParams.type=='1'&&myPdf.length==0){
                layer.msg("请上传报名表");
                return false
            }
            if(myParams.type=='1'){
                let applyForm=[]
                for (let i = 0; i < myPdf.length; i++) {
                    applyForm.push(myPdf[i].url)
                }
                myParams.applyForm=applyForm.join(',')
            }
            if(myParams.type=='2'&&myPdfs.length==0){
                layer.msg("请上传个人照片");
                return false
            }
            if(myParams.type=='2'){
                let userImg=[]
                for (let i = 0; i < myPdfs.length; i++) {
                    userImg.push(myPdfs[i].url)
                }
                myParams.userImg=userImg.join(',')
            }
            console.log('获取后面的',myParams)
            AjaxPost('/jzweb/jazSignupUser/updateSignupUser', {
                ...myParams
            }).then(function (response) {
                parent.layer.msg("操作成功");
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                parent.load();
            }).catch(error => {
                layer.msg(error.msg)
            })

        }
    });
});
var removeImg= (id) => {
    console.log('删除',id+'-0',myPdf)
    if (myPdf.find(item => item.id == id + '-0')) {
        //删除这条
        myPdf = myPdf.filter((item) => {
            return !(id + '-0').includes(item.id)
        });
        $('#myUpdataList').find('div[myid=' + id + '-0]').remove();
    }
    event.stopPropagation();
}
var removeImgs= (id) => {
    console.log('删除',id+'-0',myPdfs)
    if (myPdfs.find(item => item.id == id + '-0')) {
        //删除这条
        myPdfs = myPdfs.filter((item) => {
            return !(id + '-0').includes(item.id)
        });
        $('#myUpdataImageList').find('div[myid=' + id + '-0]').remove();
    }
    event.stopPropagation();
}

var openPdf = (id) => {
    let myItem = myPdf.find(item => item.id == id + '-0')
    // let toIndex = layer.open({
    //     type: 2,
    //     area: ['80%', '80%'],
    //     fixed: false, //不固定
    //     maxmin: true,
    //     content: myItem.url
    // });
    let a= document.createElement("a");
    a.href= myItem.url
    a.download= myItem.url.substr(myItem.url.lastIndexOf("/"))
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    return false;
}
const refused=()=>{
    if($('#status').val()=='1'){
        //待审核
    }
    layer.prompt({title: '请输入拒绝原因', formType: 2}, function(value, index, elem){
        if(value === ''){
            parent.layer.msg("请输入拒绝原因");
            return elem.focus();
        }
        // 关闭 prompt
        AjaxPost('/jzweb/jazSignupUser/update', {
            id:$('#userId').val(),
            status:2,
            result:2,
            refuseReasion:value
        }).then(function (response) {
            parent.layer.msg("操作成功");
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            layer.close(index);
            parent.layer.close(index);
            parent.load();
        }).catch(error => {
            layer.msg(error.msg)
        })
    });
}
var openPdfUrl = (url) => {
    // console.log('url',url,url.endsWith('.pdf'))
    // if(url.endsWith('.pdf')){
    //     //https
    //     let http= window.location.href.substring(0,5)=='http:'
    //     let myurl= url.indexOf('http:')==0?url.replace('http:',''):url.replace('https:','')
    //   let toIndex = layer.open({
    //     type: 2,
    //     area: ['80%', '80%'],
    //     fixed: false, //不固定
    //     maxmin: true,
    //     content: myurl
    //   });
    // return false
    // }else{
        let a= document.createElement("a");
        a.href=url
        a.download="报名表"+url.substr(url.lastIndexOf('.'))
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    // }
}

const updateCount=(textarea)=> {
    var currentLength = textarea.value.length;
    document.getElementById('currentChars').innerText = currentLength;
}

